<template>
	<view class="bg-[#FFFFFF] px-[16px] pt-[16px]">
		<u-form ref="formRef" labelPosition="left" label-width="100px" borderBottom :rules="rules" :model="formData">
			<u-form-item label="充值金额" prop="Amount">
				<u-input v-model="formData.Amount" border="none" type="number" placeholder="请输入充值金额" clearable></u-input>
			</u-form-item>
			<u-form-item label="凭证附件">
				<u-upload :fileList="ImageUrl" @afterRead="afterRead"	@delete="deletePic" multiple :maxCount="9" ></u-upload>
			</u-form-item>			
			<u-form-item label="备注" prop="Remark">
				<u-input v-model="formData.Remark" border="none" placeholder="请输入备注" clearable></u-input>
			</u-form-item>
		</u-form>
	</view>
	<u-gap height="60"></u-gap>
	<u-button @click="toSubmit" class="mx-[16px]" text="提交" size="large" shape="circle" type="error"></u-button>
</template>

<script setup>
	import { nextTick, ref, unref } from "vue";
	import * as api from "@/api.js";
	import * as uniapp from "@dcloudio/uni-app";
	import { useUserStore } from "@/store/config.js";
	
	const store = useUserStore();
	
	const formRef = ref();
	
	const formData = ref({
		Amount: '',
		Remark: ''
	})
	
	const ImageUrl=ref([]);
	
	const rules = {
		Amount: {
			type: 'number',
			required: true,
			message: '请填写充值金额',
			trigger: 'blur'
		}
	}
	
	// 删除图片
	const deletePic = (event) => {
	  ImageUrl.value.splice(event.index, 1);
	};
	
	//新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file);
	  let fileListLen = ImageUrl.value.length;
	  lists.map((item) => {
	    ImageUrl.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await api.uploadImg(lists[i].url);
		if(result[0]){
			let item = ImageUrl.value[fileListLen];
			ImageUrl.value.splice(fileListLen, 1, {
			  ...item,
			  status: 'success',
			  message: '',
			  url: JSON.parse(result[0]).data.FileUrl,
			});
			fileListLen++;
		}
	  }
	};
	
	const toSubmit = () => {
		formRef.value.validate().then(async res => {
			uni.showLoading();
			const result = await api.recharge(store.user.UserID,{...unref(formData),ImageUrl:ImageUrl.value.map((it)=>it.url)});
			uni.hideLoading();
			await nextTick();
			if(result[1]) {
				uni.showToast({
					icon:'none',
					title:result[1]
				})
			} else {
				uni.showToast({
					icon:'success',
					title:'提交成功'
				})
				await uni.$u.sleep(800);
				uni.navigateBack();
			}
		}).catch(err => console.log(err))
	}
</script>

<style>
	       
</style>
